#include "StdAfx.h"
#include "SourceCodeHandler.h"

void ReplaceCommentAndTextLiteral(const CAtlStringW & rSourceCode, OUT CAtlStringW & rOutput)
{
	rOutput = rSourceCode;
	//replace content of source code in comments and conten of text literal with ' '
	for(int n = 0, nCount = rOutput.GetLength(); n < nCount; ++n)
	{
		int nDist = -1;
		wchar_t c = rOutput.GetAt(n);
		switch(c)
		{
		case L'\\':
			++n; //ignore next one
			break;
		case L'\'':
		case L'\"':
			++n;
			nDist = n;

			while ((-1 != (nDist = rOutput.Find(c, nDist))) && (rOutput.GetAt(nDist - 1) == L'\\')) 
				++nDist; //igonre \" or \'

			if (nDist == -1)
				nDist = nCount;
			break;
		case L'/':
			if (n + 1 < nCount)
			{
				switch(rOutput.GetAt(n + 1))
				{
				case L'*':
					nDist = rOutput.Find(L"*/", n + 2);
					if (nDist != -1) 
						nDist += 2; //ignore "*/"
					else
						nDist = nCount;
					break;
				case L'/':
					nDist = rOutput.Find(L'\n', n + 2);
					if (nDist == -1)
						nDist = nCount;
					else if (rOutput.GetAt(nDist - 1) == L'\r') 
						--nDist; //ignore '\r'
					break;
				}
			}
			break;
		}

		//replace comment with ' '
		for (;n < nDist; ++n)
			rOutput.SetAt(n, L' ');
	}
}


int FindLexeme(IN const CAtlStringW & wstr, IN LPCWSTR lpLexeme, IN int nStart)
{
	int nLen = static_cast<int>(wcslen(lpLexeme));
	int nFind = -1;
	int nCur = nStart;
	while(-1 != (nFind = wstr.Find(lpLexeme, nCur)))
	{
		nCur = nFind + 1;
		if (((0 == nFind) || (0 == iswalnum(wstr.GetAt(nFind - 1)))) &&
			((nFind + nLen == wstr.GetLength()) || (0 == iswalnum(wstr.GetAt(nFind + nLen)))))
		{
			break;	
		}
	}
	return nFind;
}